package org.hongbo.springbootebsapi.jwt;

import org.hongbo.springbootebsapi.entity.AuthUser;
import org.hongbo.springbootebsapi.service.responsibility.IResponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    Audience audience;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    private IResponService responService;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain chain) throws ServletException, IOException {

        String authHeader = request.getHeader(audience.getAuthorization());
        if (authHeader != null && authHeader.startsWith(audience.getTokenHead())) {
            final String authToken = authHeader.substring(audience.getTokenHead().length()); // The part after "Bearer "

            String requestURI = request.getRequestURI();

            if(SecurityContextHolder.getContext().getAuthentication()!=null){
                UserDetails userDetails =(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                AuthUser user = (AuthUser)userDetails;
                logger.info("SecurityContextHolder.getContext().getAuthentication()!=null "+requestURI);
                //通过此种方式来进行初始化，需要确定的是，在客户端发起一个请求之后，Java会启动一个新的线程来进行处理
                //并且在此线程的上下文当中，直到方法执行完毕，永远处于同一个数据库会话之中
                //update by hongbo,20190326
                //此处理方法并不能使整个代码处理过程处于同一个事务，事务的处理是通过@Transactional注解来保证的
                //responService.initResponsiblity();
            }

            if (SecurityContextHolder.getContext().getAuthentication() == null){
                logger.info("SecurityContextHolder.getContext().getAuthentication()==null "+requestURI);
                AuthUser user = new AuthUser(authToken);

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        user, null, user.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                        request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }

        }

        chain.doFilter(request, response);
    }

}